package org.example;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Trip {

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        if (args == null || args.length == 0) {
            args = new String[]{"D:/IdeaProject/gitee/project-hive-taxi-data-analysis/data/data.csv", "output/"};
        }
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "trip");

        job.setJarByClass(Trip.class);
        job.setMapperClass(DataPreProcessMapper.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);


        FileInputFormat.addInputPath(job, new Path(args[0]));
        Path outputPath = new Path(args[1]);
        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(outputPath)) {
            fs.delete(outputPath, true);
        }
        FileOutputFormat.setOutputPath(job, outputPath);

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }


    public static class DataPreProcessMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context)
                throws IOException, InterruptedException {
            String line = value.toString();
            // 跳过标题行
            if (line.contains("VendorID")) {
                System.err.println("跳过标题行");
                return;
            }

            String[] fields = line.split(",");

            String pickupDatetime = fields[1];
            String[] split = pickupDatetime.split("\\s+");
            String[] arr = split[0].split("-");
            String hour = split[1].split(":")[0];

            context.write(new Text(line + String.format(",%s,%s,%s,%s", arr[0], arr[1], arr[2], hour)), NullWritable.get());
        }
    }
}